import React, { useEffect, useState } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Drawer, Message } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import DataForm from './components/DataForm';

const tableId = uniqueId('tauTable-');

const TITLE_TEXT = {
  view: t`查看司机`,
  edit: t`编辑管理群`,
  add: t`添加管理群`,
};

const BobVehicle = () => {
  const { bobVehicleStore: store } = useStore();
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });

  useEffect(() => {
    (async () => {
      await store.getCompaniesNames();
      const port = await store.getDicts('port');
      const tempMenu = port.reduce((acc, cur) => {
        acc[cur.value] = cur.label;
        return acc;
      }, {});
      // eslint-disable-next-line require-atomic-updates
      store._MENU_PORTS = tempMenu;
    })();
  }, []);

  /**
   * @description 处理搜索条件
   * @param {*} params
   */
  const handleOnSearch = (params) => {
    const { onData, enable, ...searchArgs } = params.values;
    const [from, to] = onData || [];
    store.search = {
      from,
      to,
      ...(enable ? { enable: JSON.parse(enable) } : null),
      ...searchArgs,
    };
  };

  /**
   * 关闭侧边卡片
   */
  const handleCancel = () => {
    setModal({ show: null });
  };

  const handleView = (r) => {
    setModal({ show: 'view', record: r });
  };

  const handleOnSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`添加失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handleOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`更新成功` });
      } catch (e) {
        Message.error({ content: t`更新失败`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'onData',
            type: 'date-range',
            props: {
              placeholder: [t`开始时间`, t`结束时间`],
            },
          },
          {
            name: 'passengerCapacity',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS._passengerCapacity),
            },
          },
          {
            name: 'ports',
            type: 'dict-item',
            props: {
              dictId: 'port',
              mode: 'multiple',
              style: { width: 160 },
            },
          },
          {
            name: 'companyName',
            type: 'select',
            props: {
              placeholder: t`公司名称`,
              dataSource: store.companiesNames,
              style: { width: 160 },
            },
          },
        ]}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.refund)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('mainlandLicense', {}),
            column('hkLicense', {}),
            column('ports', {}),
            column('drivers', {}),
            column('vehicleModel', { width: 100 }),
            column('passengerCapacity', { width: 88 }),
            column('crDate', { width: 180 }),
            {
              title: t`操作`,
              dataIndex: 'memberNumber',
              width: 100,
              cell: (_, __, r) => (
                <>
                  <Button key={'1'} text type="primary" onClick={() => handleView(r)} >{t`查看`}</Button>
                </>),
            }]
          }
        />
      </div>
      <Drawer
        visible={modal.show === 'add' || modal.show === 'edit' || modal.show === 'view'}
        title={TITLE_TEXT[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width={'100%'}
      >
        <DataForm
          modal={modal}
          id={modal.record?.id}
          onSubmit={modal.show === 'add' ? handleOnSubmit : handleOnUpdate}
          onCancel={handleCancel}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(BobVehicle);
